package com.tc.activiti.web.form.dynamic;

import cn.hutool.core.collection.CollUtil;
import com.tc.activiti.util.BeanUtils;
import com.tc.activiti.util.Page;
import com.tc.activiti.util.PageUtil;
import com.tc.activiti.util.user.UserUtil;
import com.tc.base.constants.PageConstants;
import com.tc.base.constants.StateEnum;
import com.tc.base.entity.APIRequest;
import com.tc.base.entity.APIResult;
import com.tc.biz.entity.BpmnApproval;
import com.tc.biz.entity.DrainagePipeMaintainence;
import com.tc.biz.entity.SysUser;
import com.tc.biz.provider.BpmnBusinessProvider;
import com.tc.biz.service.BpmnApprovalService;
import com.tc.biz.service.IDrainagePipeMainService;
import com.tc.biz.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.form.StartFormDataImpl;
import org.activiti.engine.impl.form.TaskFormDataImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

/**
 * 动态表单Controller
 */
@Api(value = "动态表单流程管理器", tags = "动态表单流程管理器")
@Controller
@RequestMapping(value = "/bpmn/form/dynamic")
public class DynamicFormController2 {

    public static final Logger logger = LoggerFactory.getLogger(DynamicFormController2.class);
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    protected FormService formService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected IdentityService identityService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RuntimeService runtimeService;

    protected static Map<String, ProcessDefinition> PROCESS_DEFINITION_CACHE = new HashMap<String, ProcessDefinition>();

    @Autowired
    protected IDrainagePipeMainService drainagePipeMainService;
    @Autowired
    protected IUserService userService;
    @Autowired
    protected BpmnApprovalService bpmnApprovalService;
    @Autowired
    protected BpmnBusinessProvider bpmnBusinessProvider;

    /**
     * 读取所有的流程列表
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "读取所有的流程列表", notes = "读取所有的流程列表")
    @RequestMapping(value = "/processlist", method = RequestMethod.POST)
    @ResponseBody
    public APIResult processDefinitionList(@RequestBody APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery().orderByDeploymentId().desc();
            List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(processDefinitionList)) {
                for (ProcessDefinition processDefinition : processDefinitionList) {
                    Map<String, Object> values = new HashMap<>();
                    values.put("id", processDefinition.getId());
                    values.put("name", processDefinition.getName());
                    values.put("key", processDefinition.getKey());
                    values.put("version", processDefinition.getVersion());
                    values.put("diagramResourceName", processDefinition.getDiagramResourceName());
                    values.put("category", processDefinition.getCategory());
                    values.put("description", processDefinition.getDescription());
                    values.put("resourceName", processDefinition.getResourceName());
                    listMap.add(values);
                }
            }
            page.setTotalCount(processDefinitionQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("查询流程定义列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/processlist", e);
        }
        return result;
    }

    /**
     * 初始化启动流程，读取启动流程的表单字段来渲染start form
     */
    @ApiOperation(value = "读取启动流程的表单", notes = "读取启动流程的表单")
    @RequestMapping(value = "/get-form/start/{processDefinitionId}", method = RequestMethod.GET)
    @ResponseBody
    public APIResult findStartForm(@PathVariable("processDefinitionId") String processDefinitionId) {
        APIResult result = new APIResult<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            StartFormDataImpl startFormData = (StartFormDataImpl) formService.getStartFormData(processDefinitionId);
            startFormData.setProcessDefinition(null); //对象之间存在循环依赖，输出json会报错
            // 读取enum类型数据，用于下拉框
            List<FormProperty> formProperties = startFormData.getFormProperties();
            if (CollUtil.isNotEmpty(formProperties)) {
                for (FormProperty formProperty : formProperties) {
                    Map<String, String> values = (Map<String, String>) formProperty.getType().getInformation("values");
                    if (values != null) {
                        for (Entry<String, String> enumEntry : values.entrySet()) {
                            logger.debug("enum, key: {}, value: {}", enumEntry.getKey(), enumEntry.getValue());
                        }
                        resultMap.put("enum_" + formProperty.getId(), values);
                    }
                }
            }
            resultMap.put("form", startFormData);
            result.setData(resultMap);
            result.setMessage("读取启动流程的表单成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/get-form/start/" + processDefinitionId, e);
        }
        return result;
    }

    /**
     * 读取Task的表单
     */
    @ApiOperation(value = "读取Task的表单", notes = "读取Task的表单")
    @RequestMapping(value = "/get-form/task/{taskId}", method = RequestMethod.GET)
    @ResponseBody
    public APIResult findTaskForm(@PathVariable("taskId") String taskId) {
        APIResult result = new APIResult<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            TaskFormDataImpl taskFormData = (TaskFormDataImpl) formService.getTaskFormData(taskId);
            // 设置task为null，否则输出json的时候会报错
            taskFormData.setTask(null);
            resultMap.put("taskFormData", taskFormData);
            //读取enum类型数据，用于下拉框
            List<FormProperty> formProperties = taskFormData.getFormProperties();
            if (CollUtil.isNotEmpty(formProperties)) {
                for (FormProperty formProperty : formProperties) {
                    Map<String, String> values = (Map<String, String>) formProperty.getType().getInformation("values");
                    if (values != null) {
                        for (Entry<String, String> enumEntry : values.entrySet()) {
                            logger.debug("enum, key: {}, value: {}", enumEntry.getKey(), enumEntry.getValue());
                        }
                        resultMap.put(formProperty.getId(), values);
                    }
                }
            }
            result.setData(resultMap);
            result.setMessage("获取task表单成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/get-form/task/" + taskId, e);
        }
        return result;
    }

    /**
     * 办理任务，提交task的并保存form
     */
    @ApiOperation(value = "办理任务", notes = "办理任务")
    @RequestMapping(value = "/task/complete/{taskId}", method = RequestMethod.POST)
    @ResponseBody
    public APIResult completeTask(@PathVariable("taskId") String taskId, HttpServletRequest request) {
        APIResult result = new APIResult<>();
        try {
            Map<String, String> formProperties = new HashMap<String, String>();
            // 从request中读取参数然后转换
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) {
                String key = entry.getKey();
                // fp_的意思是form paremeter
                if (StringUtils.defaultString(key).startsWith("fp_")) {
                    formProperties.put(key.split("_")[1], entry.getValue()[0]);
                }
            }
            logger.debug("start form parameters: {}", formProperties);
            //TODO 后续需要修改
            User user = UserUtil.getUserFromSession(request.getSession());
            // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
            ProcessInstance processInstance = null;
            if (user == null || StringUtils.isBlank(user.getId())) {
                throw new RuntimeException("用户未登录，不能操作");
            } else {
                identityService.setAuthenticatedUserId(user.getId());
                formService.submitTaskFormData(taskId, formProperties);
                logger.debug("start a processinstance: {}", processInstance);
                result.setMessage("任务完成：taskId=" + taskId);
                result.setState(200);
            }
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/complete/" + taskId, e);
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return result;
    }

    /**
     * 提交启动流程
     */
    @ApiOperation(value = "提交启动流程", notes = "提交启动流程")
    @RequestMapping(value = "/start-process/{processDefinitionId}", method = RequestMethod.POST)
    @ResponseBody
    public APIResult submitStartFormAndStartProcessInstance(@PathVariable("processDefinitionId") String processDefinitionId,
                                                            HttpServletRequest request) {
        APIResult result = new APIResult<>();
        try {
            Map<String, String> formProperties = new HashMap<String, String>();
            // 从request中读取参数然后转换
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) {
                String key = entry.getKey();
                // fp_的意思是form paremeter
                if (StringUtils.defaultString(key).startsWith("fp_")) {
                    formProperties.put(key.split("_")[1], entry.getValue()[0]);
                }
            }
            logger.debug("start form parameters: {}", formProperties);
            //TODO 后续需要修改
//            User user = UserUtil.getUserFromSession(request.getSession());
            // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
            ProcessInstance processInstance = null;
          /*  if (user == null || StringUtils.isBlank(user.getId())) {
                throw new RuntimeException("用户未登录，不能操作");
            } else {

            }*/
            identityService.setAuthenticatedUserId("1");
            processInstance = formService.submitStartFormData(processDefinitionId, formProperties);
            logger.debug("start a processinstance: {}", processInstance);
            result.setMessage("启动成功，流程ID：" + processInstance.getId());
            result.setState(200);
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/start-process/" + processDefinitionId, e);
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return result;
    }


    /**
     * 获取获选人待办任务列表
     * (无区分待办和待签收)
     *
     * @param request
     * @param servletRequest
     * @return
     */
    @ApiOperation(value = "获取获选人待办任务列表(无区分待办和待签收)", notes = "获取获选人待办任务列表(无区分待办和待签收)")
    @RequestMapping(value = "/task/todo/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult taskList(@RequestBody(required = true) APIRequest request,
                              HttpServletRequest servletRequest) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            String userId = request.getParameter("userId");
            if (BeanUtils.isEmpty(userId)) {
                //TODO 后续需要修改
                User user = UserUtil.getUserFromSession(servletRequest.getSession());
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("请先登录在操作");
                }
                userId = user.getId();
            }
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            //获取获选人待办任务列表，需要判断是候选人的任务签收还是直接办理
            TaskQuery taskQuery = taskService.createTaskQuery();
            List<Task> tasks = taskQuery.taskCandidateOrAssigned(userId).active().orderByTaskCreateTime().asc().listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(tasks)) {
                for (Task task : tasks) {
                    Map<String, Object> values = new HashMap<>();
                    values.put("id", task.getId());
                    values.put("name", task.getName());
                    values.put("category", task.getCategory());
                    values.put("assignee", task.getAssignee());
                    values.put("description", task.getDescription());
                    values.put("processDefinitionId", task.getProcessDefinitionId());
                    values.put("owner", task.getOwner());
                    values.put("formKey", task.getFormKey());
                    values.put("taskDefinitionKey", task.getTaskDefinitionKey());
                    listMap.add(values);
                }
            }
            page.setTotalCount(taskQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("获取获选人待办任务列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/todo/list", e);
        }
        return result;
    }

    /**
     * 获取获选人待办任务列表
     *
     * @param request
     * @param servletRequest
     * @return
     */
    @ApiOperation(value = "获取获选人待办任务列表(区分待办和待签收)", notes = "获取获选人待办任务列表(区分待办和待签收)")
    @RequestMapping(value = "/task/todo/list2", method = RequestMethod.POST)
    @ResponseBody
    public APIResult todoTaskList(@RequestBody(required = true) APIRequest request,
                                  HttpServletRequest servletRequest) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            String userId = request.getParameter("userId");
            SysUser sysUser = userService.selectByPrimaryKey(new Long(userId));
            if (BeanUtils.isEmpty(sysUser)) throw new RuntimeException("用户不存在");
            if (BeanUtils.isEmpty(userId)) {
                //TODO 后续需要修改
                User user = UserUtil.getUserFromSession(servletRequest.getSession());
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("请先登录在操作");
                }
                userId = user.getId();
            }
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取获选人待办任务列表
            TaskQuery taskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId);
            // 待办任务   查询发起人
            List<Task> todoList = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().asc().active().list();
            if (CollUtil.isNotEmpty(todoList)) {
                for (Task task : todoList) {
                    String processDefinitionId = task.getProcessDefinitionId();
                    ProcessDefinition processDefinition = getProcessDefinition(processDefinitionId);
                    Map<String, Object> singleTask = packageTaskInfo(sdf, task, processDefinition);
                    singleTask.put("status", "todo");
                    singleTask.put("sysUser", sysUser);
                    listMap.add(singleTask);
                }
            }
            // 等待签收的任务  查询发起人
            List<Task> toClaimList = taskService.createTaskQuery().taskCandidateUser(userId).orderByTaskCreateTime().asc().active().list();
            if (CollUtil.isNotEmpty(toClaimList)) {
                for (Task task : toClaimList) {
                    String processDefinitionId = task.getProcessDefinitionId();
                    ProcessDefinition processDefinition = getProcessDefinition(processDefinitionId);
                    Map<String, Object> singleTask = packageTaskInfo(sdf, task, processDefinition);
                    singleTask.put("status", "claim");
                    singleTask.put("sysUser", sysUser);
                    listMap.add(singleTask);
                }
            }
            //listMap转换
            Long count = taskQuery.count();
            Integer totalCount = pageNo * pageSize;
            Integer countValue = count.intValue();
            if (BeanUtils.isNotEmpty(listMap)) {
                listMap = listMap.subList(pageSize * (pageNo - 1), (totalCount > countValue ? countValue : totalCount));
            }
            //转换完成之后查询任务的发起人
            for (Map<String, Object> map : listMap) {
                String taskId = (String) map.get("id");
                String startedBy = drainagePipeMainService.getStartedBy(taskId);
                SysUser user = userService.selectByPrimaryKey(new Long(startedBy));
                map.put("startedByUserId", user.getUserId());
                map.put("startedByUserName", user.getUserName());
            }
            page.setTotalCount(count);
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("获取获选人待办任务列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/todo/list2", e);
        }
        return result;
    }


    private Map<String, Object> packageTaskInfo(SimpleDateFormat sdf, Task task, ProcessDefinition processDefinition) {
        Map<String, Object> singleTask = new HashMap<String, Object>();
        singleTask.put("id", task.getId());
        singleTask.put("name", task.getName());
        singleTask.put("createTime", sdf.format(task.getCreateTime()));
        singleTask.put("pdname", processDefinition.getName());
        singleTask.put("pdversion", processDefinition.getVersion());
        singleTask.put("pid", task.getProcessInstanceId());
        return singleTask;
    }


    private ProcessDefinition getProcessDefinition(String processDefinitionId) {
        ProcessDefinition processDefinition = PROCESS_DEFINITION_CACHE.get(processDefinitionId);
        if (processDefinition == null) {
            processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
            PROCESS_DEFINITION_CACHE.put(processDefinitionId, processDefinition);
        }
        return processDefinition;
    }


    /**
     * 签收任务
     *
     * @param taskId
     * @param request
     * @return
     */
    @ApiOperation(value = "签收任务", notes = "签收任务")
    @RequestMapping(value = "/task/claim/{taskId}", method = RequestMethod.GET)
    @ResponseBody
    public APIResult claim(@PathVariable("taskId") String taskId, HttpServletRequest request) {
        APIResult result = new APIResult<>();
        try {
            String userId = request.getParameter("userId");
            if (BeanUtils.isEmpty(userId)) {
                //TODO 后续需要修改
                User user = UserUtil.getUserFromSession(request.getSession());
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("请先登录在操作");
                }
                userId = user.getId();
            }
            taskService.claim(taskId, userId);
            result.setMessage("签收任务成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/task/claim/" + taskId, e);
        }
        return result;
    }

    /**
     * 运行中的流程实例  只有权限查看自己的，如果是管理员，查看全部的运行流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "运行中的流程实例", notes = "运行中的流程实例")
    @RequestMapping(value = "/process-instance/running/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult running(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            ProcessInstanceQuery dynamicQuery = runtimeService.createProcessInstanceQuery().orderByProcessInstanceId().desc().active();
            List<ProcessInstance> list = dynamicQuery.listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(list)) {
                for (ProcessInstance processInstance : list) {
                    Map<String, Object> values = new HashMap<String, Object>();
                    values.put("id", processInstance.getId());
                    values.put("name", processInstance.getName());
                    values.put("businessKey", processInstance.getBusinessKey());
                    values.put("deploymentId", processInstance.getDeploymentId());
                    values.put("description", processInstance.getDescription());
                    values.put("processDefinitionId", processInstance.getProcessDefinitionId());
                    values.put("processDefinitionName", processInstance.getProcessDefinitionName());
                    values.put("processDefinitionVersion", processInstance.getProcessDefinitionVersion());
                    listMap.add(values);
                }
            }
            page.setTotalCount(dynamicQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("查询运行中的流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/running/list", e);
        }
        return result;
    }


    /**
     * 已结束的全部流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "已结束的全部流程实例", notes = "已结束的全部流程实例")
    @RequestMapping(value = "/process-instance/finished/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult finished(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            HistoricProcessInstanceQuery dynamicQuery = historyService.createHistoricProcessInstanceQuery().finished().orderByProcessInstanceEndTime().desc();
            List<HistoricProcessInstance> list = dynamicQuery.listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(list)) {
                for (HistoricProcessInstance historicProcessInstance : list) {
                    Map<String, Object> values = new HashMap<String, Object>();
                    values.put("id", historicProcessInstance.getId());
                    values.put("name", historicProcessInstance.getName());
                    values.put("businessKey", historicProcessInstance.getBusinessKey());
                    values.put("deploymentId", historicProcessInstance.getDeploymentId());
                    values.put("description", historicProcessInstance.getDescription());
                    values.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
                    values.put("processDefinitionName", historicProcessInstance.getProcessDefinitionName());
                    values.put("processDefinitionVersion", historicProcessInstance.getProcessDefinitionVersion());
                    listMap.add(values);
                }
            }
            page.setTotalCount(dynamicQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("已结束的全部流程实例成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/list", e);
        }
        return result;
    }

    /**
     * 查询当前登录人的已办任务
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询当前登录人的已办任务", notes = "查询当前登录人的已办任务")
    @RequestMapping(value = "/process-instance/finished/task/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult finishedByAssignee(@RequestBody(required = true) APIRequest request, HttpServletRequest servletRequest) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            String userId = request.getParameter("userId");
            SysUser sysUser = userService.selectByPrimaryKey(new Long(userId));
            if (BeanUtils.isEmpty(sysUser)) throw new RuntimeException("用户不存在");
            if (BeanUtils.isEmpty(userId)) {
                //TODO 后续需要修改
                User user = UserUtil.getUserFromSession(servletRequest.getSession());
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("请先登录在操作");
                }
                userId = user.getId();
            }
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
            List<HistoricTaskInstance> taskList = historicTaskInstanceQuery.taskAssignee(userId).orderByHistoricTaskInstanceEndTime().finished().listPage(pageParams[0], pageParams[1]);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (CollUtil.isNotEmpty(taskList)) {
                for (HistoricTaskInstance historicTaskInstance : taskList) {
                    Map<String, Object> values = new HashMap<String, Object>();
                    String taskId = historicTaskInstance.getId();
                    values.put("sysUser", sysUser);//已办任务人
                    values.put("taskId", taskId);
                    values.put("name", historicTaskInstance.getName());
                    values.put("durationInMillis", historicTaskInstance.getDurationInMillis());
                    values.put("endTime", sdf.format(historicTaskInstance.getEndTime()));
                    values.put("startTime", sdf.format(historicTaskInstance.getStartTime()));
                    values.put("description", historicTaskInstance.getDescription());
                    values.put("processDefinitionId", historicTaskInstance.getProcessDefinitionId());
                    values.put("claimTime", historicTaskInstance.getClaimTime());
                    values.put("getWorkTimeInMillis", historicTaskInstance.getWorkTimeInMillis());
                    //状态 同意还是拒绝
                    String processInstanceId = historicTaskInstance.getProcessInstanceId(); //实例id
                    ProcessInstance processInstance =
                            runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                    String processDefinitionId = processInstance.getProcessDefinitionId();
                    String name = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult().getName();
                    //设置标题
                    values.put("processDefinitionName", name);
                    //查询流程是由谁发起的
                    String startedBy = drainagePipeMainService.getStartedBy(taskId);
                    SysUser user = userService.selectByPrimaryKey(new Long(startedBy));
                    values.put("startByUser", user);
                    //设置流程的审批状态
                    BpmnApproval approval = bpmnApprovalService.findByTaskId(taskId);
                    values.put("opinion", approval.getOpinion());
                    listMap.add(values);
                }
            }
            page.setTotalCount(historicTaskInstanceQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("查询当前登录人的已办任务成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/task/list", e);
        }
        return result;
    }


    /**
     * 查询已结束的流程实例
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询已结束的流程实例", notes = "查询已结束的流程实例")
    @RequestMapping(value = "/process-instance/findBpmnInstDetail", method = RequestMethod.POST)
    @ResponseBody
    public APIResult findBpmnInstDetail(@RequestBody(required = true) APIRequest request) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            HistoricProcessInstanceQuery dynamicQuery = historyService.createHistoricProcessInstanceQuery().finished().orderByProcessInstanceEndTime().orderByProcessInstanceStartTime().desc();
            List<HistoricProcessInstance> list = dynamicQuery.listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(list)) {
                for (HistoricProcessInstance historicProcessInstance : list) {
                    Map<String, Object> values = new HashMap<String, Object>();
                    values.put("id", historicProcessInstance.getId());
                    values.put("name", historicProcessInstance.getName());
                    values.put("businessKey", historicProcessInstance.getBusinessKey());
                    values.put("deploymentId", historicProcessInstance.getDeploymentId());
                    values.put("description", historicProcessInstance.getDescription());
                    values.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
                    values.put("processDefinitionName", historicProcessInstance.getProcessDefinitionName());
                    values.put("processDefinitionVersion", historicProcessInstance.getProcessDefinitionVersion());
                    listMap.add(values);
                }
            }
            page.setTotalCount(dynamicQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("查询已结束的流程实例");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/finished/list", e);
        }
        return result;
    }


    /**
     * 查询我发起的流程
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询我发起的流程", notes = "查询我发起的流程")
    @RequestMapping(value = "/process-instance/startByUserId/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult findBpmnInstByStartUserId(@RequestBody(required = true) APIRequest request, HttpServletRequest servletRequest) {
        APIResult<Page> result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        Page<Map<String, Object>> page = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            String userId = request.getParameter("userId");
            SysUser sysUser = userService.selectByPrimaryKey(new Long(userId));
            if (BeanUtils.isEmpty(sysUser)) throw new RuntimeException("用户不存在");
            //TODO 后续需要修改
            if (BeanUtils.isEmpty(userId)) {
                //to_do  zengqingfa
                User user = UserUtil.getUserFromSession(servletRequest.getSession());
                if (BeanUtils.isEmpty(user)) {
                    throw new RuntimeException("请先登录在操作");
                }
                userId = user.getId();
            }
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            page = new Page<>(pageSize);
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            HistoricProcessInstanceQuery historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery().orderByProcessInstanceEndTime().desc();
            List<HistoricProcessInstance> list = historicProcessInstanceQuery.startedBy(userId).listPage(pageParams[0], pageParams[1]);
            if (CollUtil.isNotEmpty(list)) {
                for (HistoricProcessInstance historicProcessInstance : list) {
                    Map<String, Object> values = new HashMap<String, Object>();
                    String processInstanceId = historicProcessInstance.getId();
                    values.put("historicProcessInstance", historicProcessInstance);
                    if (BeanUtils.isNotEmpty(historicProcessInstance.getEndTime())) {
                        //流程结束
                        values.put("endTime", sdf.format(historicProcessInstance.getEndTime()));
                        values.put("status", "end");
                    } else {
                        //流程未结束
                        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                        values.put("status", "running");
                        values.put("activityId", processInstance.getActivityId());
                    }
                    //各个已审批流程的信息
                    List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
                    List<HashMap<String, Object>> taskDetail = bpmnBusinessProvider.getTaskDetail(historicTaskInstanceList);
                    values.put("taskDetail", taskDetail);
                    values.put("durationInMillis", historicProcessInstance.getDurationInMillis());
                    listMap.add(values);
                }
            }
            page.setTotalCount(historicProcessInstanceQuery.count());
            page.setResult(listMap);
            result.setData(page);
            result.setMessage("查询发起的流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/form/dynamic/process-instance/startByUserId/list", e);
        }
        return result;
    }
}
